/* Страница со скриптами */
$(() => {
	if (window.location.href.indexOf('teach') > 0) {
		let dayly_show_banner = getCookie('closed_banner');

		if (typeof dayly_show_banner == 'undefined') {
			$.ajax({
				url: window.location.origin + '/banner_settings',
				type: 'get',
				dataType: 'html',
				async: true,
				success: function (data) {
					let block_order =
						'.lite-page > div:nth-of-type(1).banner_settings_block ';

					let banner_settings = {
						banner_font: {},
						top_text: getTxtProp(
							$(data).find(block_order + '.top_banner_text')
						),
						bottom_text: getTxtProp(
							$(data).find(block_order + '.bottom_banner_text')
						),
						button: getButtonProp(
							$(data).find(block_order + '.banner_button'),
							$(data).find(block_order + '.banner_button_hover')
						),
						image: getImgProp(
							$(data).find(block_order + '.banner_photo'),
							$(data).find(block_order + '.banner_bg'),
							$(data).find(block_order + '.banner_bg_color')
						),
					};

					/* Шрифты баннера  */
					banner_settings['banner_font']['top_font_txt'] = $(data)
						.find(block_order + '.banner_top_text_font .f-subheader')
						.text();
					banner_settings['banner_font']['bottom_font_txt'] = $(data)
						.find(block_order + '.banner_bottom_text_font .f-subheader')
						.text();
					banner_settings['banner_font']['font_button'] = $(data)
						.find(block_order + '.banner_button_font .f-subheader')
						.text();

					$('.gc-main-content').after(`
        	<style>
        		:root {
        			/* Шрифт верхнего текста баннера */
        			--top_font_txt: ${banner_settings['banner_font']['top_font_txt']}, sans-serif;
        			/* Шрифт ниженго текста баннера */
        			--bottom_font_txt: ${banner_settings['banner_font']['bottom_font_txt']}, sans-serif;
        			/* Шрифт кнопки баннера */
        			--font_button: ${banner_settings['banner_font']['font_button']}, sans-serif;
        			
        			/* Цвет фона баннера */
        			--banner_bg: ${banner_settings['image']['bg_color']};
        			
							/* Размер верхнего текста */
							--top_txt_size: ${banner_settings['top_text']['size']};
							/* Цвет верхнего текста */
							--top_txt_color: ${banner_settings['top_text']['color']};
							
							/* Размер нижнего текста */
							--bottom_txt_size: ${banner_settings['bottom_text']['size']};
							/* Цвет нижнего текста */
							--bottom_txt_color: ${banner_settings['bottom_text']['color']};
							
							/* Показывать кнопку или нет */
							--button_show: ${banner_settings['button']['show']};
							/* Цвет кнопки */
							--button_bg: ${banner_settings['button']['background']};
							/* Цвет кнопки при наведении */
							--button_bg_hover: ${banner_settings['button']['background_hover']};
							/* Размер текста кнопки */
							--button_fontSize: ${banner_settings['button']['fontSize']};
							/* Цвет текста кнопки */
							--button_color: ${banner_settings['button']['color']};
							/* Цвет текста кнопки при наведении */
							--button_color_hover: ${banner_settings['button']['color_hover']};
							/* Радиус скругления границ кнопки */
							--button_radius: ${banner_settings['button']['radius']};
	            /* Цвет границы кнопки */
	              --button_border_color: ${banner_settings['button']['border']};
        		}
        	</style>
					<div class="admin_banner ${banner_settings['image']['nophoto']} ${banner_settings['button']['onPhoto']} ${banner_settings['button']['noButton']}" style="${banner_settings['image']['bg']}">
						<div onCLick="goLink('${banner_settings['button']['link']}')">
							<div class="top_text">${banner_settings['top_text']['text']}</div>
							<div class="bottom_text">${banner_settings['bottom_text']['text']}</div>
							<img class="object_img" src="${banner_settings['image']['photo']}">
							<button class="go_link">${banner_settings['button']['text']}</button>
						</div>
						<span class="close_banner_24">X</span>
					</div>
				`);
				
					$('.common-banner-wrapper').remove();

					$('.close_banner_24').on('click', function () {
						$('.admin_banner').hide();
						setCookie('closed_banner', 'true', {
							secure: true,
							'max-age': 86400,
						});
					});

					console.log(banner_settings);
				},
			});
		}
	}
});

/* Обработка свойств текста */
function getTxtProp(elBlock) {
	let props = {};

	props['text'] = $(elBlock).find('div').html();
	props['size'] = $(elBlock).find('div').attr('style').split(': ')[1];
	props['color'] = $(elBlock).attr('style').split('; ');
	props['color'].forEach((prop) => {
		if (prop.split(':')[0] == 'color') {
			props['color'] = prop.split(': ')[1];
			return;
		}
	});

	return props;
}

/* Обработка свойств кнопки */
function getButtonProp(elBtn, elBtnHover) {
	let props = {};

	props['show'] = 'inline-block';
	props['noButton'] = '';
	props['onPhoto'] = '';

	if ($(elBtn).hasClass('hide_on_banner')) {
		props['show'] = 'none';
		props['noButton'] = 'noButton';
	}
	
	if ($(elBtn).hasClass('onPhoto')) {
		props['onPhoto'] = 'onPhoto';
	}
	
	props['text'] = $(elBtn).find('button').text();
	
	let button_block_style = $(elBtn).attr('style').split('; ');
	let button_style = $(elBtn).find('button').attr('style').split('; ');
	button_style = button_block_style.concat(button_style);
	
	button_style.forEach((prop) => {
		if (prop !== '') {
			if (prop.split(':')[0] == 'color') {
				props['color'] = prop.split(': ')[1];
			}
			if (prop.split(':')[0] == 'background-color') {
				props['background'] = prop.split(': ')[1];
			}
			if (prop.split(':')[0] == 'border-radius') {
				props['radius'] = prop.split(': ')[1];
			}
			if (prop.split(':')[0] == 'box-shadow') {
				props['border'] = '#' + prop.split('#')[1];
			}
			if (prop.split(':')[0] == 'margin-bottom') {
				props['fontSize'] = prop.split(': ')[1];
			}
		}
	});
	
	let button_style_hover = $(elBtnHover)
		.find('button')
		.attr('style')
		.split('; ');
		
	button_style_hover.forEach((prop) => {
		if (prop !== '') {
			if (prop.split(':')[0] == 'color') {
				props['color_hover'] = prop.split(': ')[1];
			}
			if (prop.split(':')[0] == 'background-color') {
				props['background_hover'] = prop.split(': ')[1];
			}
		}
	});
	
	let button_link = $(elBtn).find('script').text();
	const regex = /location\.href=['"]([^'"]+)['"]/;
	props['link'] = button_link.match(regex)[1];

	return props;
}

/* Обработка изображений */
function getImgProp(elImg, elBgImg, elBg) {
	let props = {};

	props['photo'] = $(elImg).find('div').attr('data-img-src');

	if (props['photo'] == '') {
		props['nophoto'] = 'nophoto';
	} else {
		props['nophoto'] = 'photo';
	}

	props['bg_color'] = $(elBg).attr('style').split('; ');
	props['bg'] = $(elBgImg).find('div').attr('data-img-src');
	props['bg_color'].forEach((prop) => {
		if (prop.split(':')[0] == 'color') {
			if (prop.split(':')[1].indexOf('linear') > -1) {
				props['bg'] =
					'background: url(' + props['bg'] + '), ' + prop.split(': ')[1];
				return;
			} else {
				props['bg_color'] = prop.split(': ')[1];
				props['bg'] = 'background-image: url(' + props['bg'] + ')';
				return;
			}
		}
	});

	return props;
}

/* Открыть ссылку при клике на баннер в новом окне */
function goLink(link) {
	window.open(link, '_blank').focus();
}

/* Проверить скрыт ли баннер */
function getCookie(name) {
	let matches = document.cookie.match(
		new RegExp(
			'(?:^|; )' +
				name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') +
				'=([^;]*)'
		)
	);
	return matches ? decodeURIComponent(matches[1]) : undefined;
}

/* Скрыть баннер на 24 часа */
function setCookie(name, value, options = {}) {
	options = {
		path: '/',
		...options,
	};

	if (options.expires instanceof Date) {
		options.expires = options.expires.toUTCString();
	}

	let updatedCookie =
		encodeURIComponent(name) + '=' + encodeURIComponent(value);

	for (let optionKey in options) {
		updatedCookie += '; ' + optionKey;
		let optionValue = options[optionKey];
		if (optionValue !== true) {
			updatedCookie += '=' + optionValue;
		}
	}

	document.cookie = updatedCookie;
}
